package com.whatever;

import java.util.Timer;
import java.util.TimerTask;

import com.whatever.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.*;

public class NewGameActivity extends Activity {
    
	private static boolean hasRun = false;
	private static boolean isDone;
	public static boolean madeHighScores;
	private long refTime;
	public static int[] scores = {0,0,0,0,0};
	public static String[] highScoreNames = {"Empty","Empty","Empty","Empty","Empty"};
	public static Integer newScore;
	private static int delayer;
	private int spawnNum;
	private int spawnIncrement;
	private int spawnInterval = 3500;
	private int gameDuration;
	private Context cxt = this;
	private DrawView drawView;
	private FrameLayout layout0;
	private static TextView textView;
	private Timer timer;
	private static Bundle savedScores;
	private Handler handler = new Handler() {
		@Override
		public synchronized void handleMessage(Message msg) { //When the timer repeats, a new thread is created executing this handler

			System.out.println("Message Recieved");
			if(!isDone) { //As long as the game isn't over yet...
				//System.out.println("Balls displayed:"+ drawView.getNumBalls());
				//System.out.println(drawView.colorBall.size());
				if(System.currentTimeMillis() - refTime >= gameDuration) { //If there are more than 50 balls on the screen at once...

					finishGame(); //End the game
					isDone = true;
					return;
				}

				drawView.createBall(spawnNum); //Create a new ball in drawView
				spawnNum = 4 + spawnIncrement; //Add a constantly growing number to spawnNum to make balls spawn faster
				spawnIncrement = (int) (((System.currentTimeMillis() - refTime) / 1000) / 20); //Set increment with which to increase spawnNum with equation to increase over time
				
				if(ColorBall.getAverageRadius() >= 60) { //As long as the colorBalls have an average radius of 60 or higher...
					ColorBall.subtractRadius(1); //Subtract 1 from the average radius
				}
				if(delayer % 3 == 0 && ColorBall.getAverageVel() <= 20) { //Every three timer runs...
					ColorBall.addVel(1); //Increase the balls' velocities by 1
					delayer++; //Add one to the delayer count
				}
			}
			System.out.println("Message complete");
		}
		
	};
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        isDone = false; //When the game starts, mark that the game is not done
        madeHighScores = false; //Initialize madeHighScores as false; will turn true if player gets high score
        newScore = 0; //Initialize this game's score at 0
        
        //if(!hasRun) { //If the activity hasn't been run yet...
        //	Intent title = new Intent(cxt, titleActivity.class); //Create a new intent pointing to the title screen
        //	cxt.startActivity(title); //Switch to the title screen
        //	hasRun = true; //Notify that the activity has been run
        //}

        gameDuration = titleActivity.getGameDuration() * 1000; //Get game duration and convert to milliseconds
        spawnIncrement = 0; //Number to increase spawnNum by starts at 0
        delayer = 0; //Int to delay the incresing velocity of the balls
        refTime = System.currentTimeMillis(); //Time to reference start of game by
        textView = (TextView)findViewById(R.id.mainTextView0); //Find textView on screen
        layout0 = (FrameLayout)findViewById(R.id.mainFrameLayout0); //Find framelayout (to put drawView in)
        timer = new Timer(); //Create a new timer to run game

        textView.setText(new StringBuilder().append(newScore)); //start score counter with beginning score (starts at 0)
        layout0.addView(drawView = new DrawView(this)); //Add the DrawView to the FrameView, to make it appear on-screen
        
        timer.scheduleAtFixedRate(new TimerTask() {
        	@Override
        	public void run() {
        		System.out.println("Sent New Message");
        		handler.sendMessage(handler.obtainMessage());
        	}
        }, 0, spawnInterval);
    }
    
    public static void incrementScore(int s) {
    	newScore += s;
    }
    
    public static void updateScore() {
    	textView.setText(new StringBuilder().append(newScore));
    }
    
    public void finishGame() {
    	isDone = true;
		timer.cancel();
		timer.purge(); //Stop the timer
		calcScore(drawView.getBallsDestroyed(), gameDuration);
    	saveScore();
    	Intent finish = new Intent(cxt, FinishScreen.class);
		cxt.startActivity(finish);
    }
    
    public int calcScore(int b, int t) {
    	return (int)(b/t);
    }
    
    public void saveScore() {
    	//scores = savedScores.getIntArray("Scores"); //Load high scores
    	//highScoreNames = savedScores.getStringArray("Names"); //Load high score names
    	/*for(int i = 0; i < scores.length; i++) { //For every score...
    		if(newScore > scores[i]) { //If current score is higher than selected score...
    			int temp = scores.length - 1;
    			while (temp > i) { //While there are still entries left below current high score...
    				scores[temp] = scores[temp - 1]; //Shift scores down one index
    				highScoreNames[temp] = highScoreNames[temp - 1]; //Shift score names down one index
    				temp--;
    			}
    			scores[i] = newScore; //The (now empty) array slot is set to the new high score
    			highScoreNames[i] = titleActivity.getPlayerName();
    			madeHighScores = true; //Inform that this player made the high scores list
    			return;
    		}
    	}*/
    	//savedScores.putIntArray("Scores", scores); //Save altered scores
    	//savedScores.putStringArray("Names", highScoreNames); //Save altered score names
    	//onSaveInstanceState(savedScores);
    }
}